<script setup lang="ts">
import type { FormSchemaGetter } from '#/adapter/form';
import type { InterviewQuestionCategoryForm } from '#/api/interview/category/model';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { addFullName, listToTree } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  addCategory,
  getCategoryInfo,
  getCategoryList,
  updateCategory,
} from '#/api/interview/category';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

// 表单配置
const schemas: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'categoryId',
    label: '分类主键',
  },
  {
    component: 'TreeSelect',
    fieldName: 'parentId',
    label: '父级分类',
    componentProps: {
      placeholder: '请选择父级分类',
      treeData: [],
      fieldNames: { label: 'categoryName', value: 'categoryId' },
      treeDefaultExpandAll: true,
      treeLine: { showLeafIcon: false },
      treeNodeLabelProp: 'fullName',
      showSearch: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'categoryName',
    label: '分类名称',
    rules: 'required',
    componentProps: {
      placeholder: '请输入分类名称',
    },
  },
  {
    component: 'Input',
    fieldName: 'icon',
    label: '图标',
    componentProps: {
      placeholder: '请输入图标地址',
    },
  },
  {
    component: 'Textarea',
    fieldName: 'categoryDescription',
    label: '分类描述',
    componentProps: {
      placeholder: '请输入分类描述',
      rows: 3,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'orderNum',
    label: '显示顺序',
    defaultValue: 0,
    componentProps: {
      min: 0,
      placeholder: '请输入显示顺序',
    },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      options: [
        { label: '正常', value: '0' },
        { label: '停用', value: '1' },
      ],
    },
    defaultValue: '0',
    fieldName: 'status',
    label: '状态',
    rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '备注',
    componentProps: {
      placeholder: '请输入备注',
      rows: 3,
    },
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
  },
  layout: 'vertical',
  schema: schemas(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [BasicDrawer, drawerApi] = useVbenDrawer({
  onCancel: handleCancel,
  onConfirm: handleConfirm,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);
    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    // 加载父级分类下拉选项
    await setupParentCategorySelect(id);

    if (isUpdate.value && id) {
      // 获取详情
      getCategoryInfo(id).then((res) => {
        formApi.setValues(res);
      });
    }

    drawerApi.drawerLoading(false);
  },
});

// 设置父级分类下拉选项
async function setupParentCategorySelect(currentId?: number | string) {
  try {
    // 获取所有分类列表
    const res = await getCategoryList({ status: '0' });
    // 过滤掉当前编辑的分类，避免自己作为自己的父级分类
    let categories = res.rows;
    if (currentId) {
      categories = res.rows.filter((item: any) => item.categoryId != currentId);
    }

    // 转换为树形结构
    const treeData = listToTree(categories, {
      id: 'categoryId',
      pid: 'parentId',
      children: 'children',
    });
    
    // 添加全名，显示层级关系
    addFullName(treeData, 'categoryName', ' / ');
    
    // 添加"无父级"选项作为根节点
    const finalTreeData = [
      {
        categoryId: 0,
        categoryName: '无父级分类',
        children: treeData,
      },
    ];

    formApi.updateSchema([
      {
        componentProps: {
          treeData: finalTreeData,
        },
        fieldName: 'parentId',
      },
    ]);
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
}

async function handleConfirm() {
  try {
    drawerApi.drawerLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = await formApi.getValues();
    // 处理父级分类ID为0的情况，表示无父级分类
    if (data.parentId === 0) {
      data.parentId = null;
    }
    await (isUpdate.value
      ? updateCategory(data as InterviewQuestionCategoryForm)
      : addCategory(data as InterviewQuestionCategoryForm));
    drawerApi.close();
    emit('reload');
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

async function handleCancel() {
  drawerApi.close();
  await formApi.resetForm();
}

async function handleSubmit(values: InterviewQuestionCategoryForm) {
  await (isUpdate.value ? updateCategory(values) : addCategory(values));
  drawerApi.close();
  drawerApi.setData({ reload: true });
}

function handleInit() {
  const { id } = drawerApi.getData() as { id?: number | string };
  isUpdate.value = !!id;

  if (isUpdate.value) {
    // 获取详情
    getCategoryInfo(id).then((res) => {
      formApi.setValues(res);
    });
  } else {
    formApi.resetFields();
  }
}

defineExpose({ handleInit });
</script>

<template>
  <BasicDrawer
    :close-on-click-modal="false"
    :title="title"
    class="w-[600px]"
    @init="handleInit"
  >
    <BasicForm @submit="handleSubmit" />
  </BasicDrawer>
</template>